//
//  USCoreDataStack.m
//  us
//
//  Created by karry on 2025/4/17.
//

#import "USCoreDataStack.h"

@interface USCoreDataStack ()
@property (nonatomic, strong) NSPersistentContainer *persistentContainer;
@end

@implementation USCoreDataStack

+ (instancetype)shared {
    static USCoreDataStack *instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[USCoreDataStack alloc] init];
        [instance setup];
    });
    return instance;
}

- (void)setup {
    // ⚠️ 请确保这里的名称和 .xcdatamodeld 文件一致（不要加后缀）
    NSString *modelName = @"USModelRecord";  // ← 改成你自己的模型名
    self->_persistentContainer = [[NSPersistentContainer alloc] initWithName:modelName];
    
    [self.persistentContainer loadPersistentStoresWithCompletionHandler:^(NSPersistentStoreDescription *desc, NSError *error) {
        if (error) {
            NSLog(@"❌ Core Data 初始化失败: %@", error.localizedDescription);
        }
    }];
}

- (NSManagedObjectContext *)context {
    return self.persistentContainer.viewContext;
}

- (void)save {
    NSManagedObjectContext *ctx = self.context;
    if (ctx != nil && ctx.hasChanges) {
        NSError *error = nil;
        if (![ctx save:&error]) {
            NSLog(@"❌ Core Data 保存失败: %@", error.localizedDescription);
        }
    }
}

@end
